import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 使用相对路径，配合vite代理
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: true // 允许跨域携带cookie
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户登录接口
export const userLogin = (data) => {
  return api.post('/user/login', {
    username: data.username,
    password: data.password
  })
}

// 管理员登录接口
export const adminLogin = (data) => {
  return api.post('/admin/login', {
    username: data.username,
    password: data.password
  })
}

// 登录接口（根据角色选择）
export const login = (data) => {
  if (data.role === 'admin') {
    return adminLogin(data)
  } else {
    return userLogin(data)
  }
}

// 注册接口
export const register = (data) => {
  return api.post('/user/register', {
    username: data.username,
    email: data.email,
    phone: data.phone,
    password: data.password,
    role: data.role
  })
}

// 获取用户信息接口
export const getUserInfo = () => {
  return api.get('/user/info')
}

// 获取管理员信息接口
export const getAdminInfo = () => {
  return api.get('/admin/info')
}



// 更新用户信息接口
export const updateUserInfo = (data) => {
  return api.post('/user/updateUserInfo', {
    id: data.id,
    avatar: data.avatar,
    email: data.email,
    phone: data.phone
  })
}

// 上传图片接口
export const uploadAvatar = (file) => {
  const formData = new FormData();
  formData.append('file', file);
  return api.post('/user/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export default api
